#include"exti.h"
#define RC_NUM  6
uint32 nowRxTime;
uint32 RxChStart[RC_NUM];
uint32 RxCh[RC_NUM]; 
volatile uint16_t rcPinValue[8] = {1500,1500,1500,1500,1500,1500,1500,1500}; // interval [1000;2000]
static int16_t rcData4Values[8][4];
static int16_t rcDataMean[8] ;

// ***PPM SUM SIGNAL***
#ifdef SERIAL_SUM_PPM
static uint8_t rcChannel[8] = {SERIAL_SUM_PPM};
#endif
volatile uint16_t rcValue[8] = {1500,1500,1500,1500,1500,1500,1500,1500}; // interval [1000;2000]
 
 
#if defined(MYCOPTER_V2)
const int RCInputPin[RC_NUM]={13,11,37,12,10,3};
#endif
#if defined(MYCOPTER_V4)
const int RCInputPin[RC_NUM]={1,12,11,0,3,2};
#endif
// Configure each rc pin for PCINT
void configureReceiver()
{
  for(int i=0;i<RC_NUM;i++)
  {
      pinMode(RCInputPin[i], INPUT_PULLUP );  
      attachInterrupt(RCInputPin[i],handler_RCInput, CHANGE);
  }
 
}
 
void handler_RCInput(void)
{
  uint32 intMask;
  uint32 CurIntStat =  EXTI_BASE->PR;
   nowRxTime=micros();
  for(int i=0;i<sizeof(RCInputPin)/sizeof(int);i++)
  {
    intMask=BIT(PIN_MAP[RCInputPin[i]].gpio_bit);//取得中断对应的位
    
   if(intMask&CurIntStat)//有中断
   {  
       *bb_perip(&EXTI_BASE->PR, PIN_MAP[RCInputPin[i]].gpio_bit) = 1;
       
       if(digitalRead(RCInputPin[i])==HIGH)
       {
         RxChStart[i]=nowRxTime;
       }
       else
       {//low
          RxCh[i]=nowRxTime-RxChStart[i];    
         if (900<RxCh[i] && RxCh[i]<2200) 
         { rcValue[i]= RxCh[i];               
          if(i==THROTTLE){ if(failsafeCnt > 20) failsafeCnt -= 20; else failsafeCnt = 0; } 
          } 
       }
     }
    
  }
                     
}
 

uint16_t readRawRC(uint8_t chan) {
  uint16_t data;
   #ifdef SERIAL_SUM_PPM      
   data = rcValue[rcChannel[chan]]; 
   #else
   data = rcValue[chan]; 
   #endif
  return data; // We return the value correctly copied when the IRQ's where disabled
}
  
void computeRC() {
  static uint8_t rc4ValuesIndex = 0;
  uint8_t chan,a;

  rc4ValuesIndex++;
  for (chan = 0; chan < 8; chan++) {
    rcData4Values[chan][rc4ValuesIndex%4] = readRawRC(chan);
    rcDataMean[chan] = 0;
    for (a=0;a<4;a++) rcDataMean[chan] += rcData4Values[chan][a];
    rcDataMean[chan]= (rcDataMean[chan]+2)/4;
    if ( rcDataMean[chan] < rcData[chan] -3)  rcData[chan] = rcDataMean[chan]+2;
    if ( rcDataMean[chan] > rcData[chan] +3)  rcData[chan] = rcDataMean[chan]-2;
  }
}

